<?php
/*
 * 注册
 */
namespace app\home\controller;

use think\Request;

class Reg extends Common {
    public function index() {
        return $this->fetch();
    }

    public function getCode() {
        if (request()->isPost()) {
            $phone = input('phone');
            $check = model('user')->getUser(['username' => $phone]);
            if ($check) {
                $this->ajaxReturn(['code' => 0, 'msg' => '手机号码已注册!']);
            }
            $res = model('phone', 'logic')->getCode([
                    'phone' => $phone,
                    'type' => 'reg',
                    'limit' => 60
            ]);
            if ($res['code'] == 1) {
                $this->ajaxReturn(['code' => 1, 'msg' => '获取验证码成功']);
            } else {
                $this->ajaxReturn($res);
            }
        }
    }

    public function reg() {
        if (request()->isPost()) {
            $phone = input('phone', '', 'intval');
            $code = input('code', '', 'intval');
            $pwd = input('pwd', '');
            $inviter = input('inviter', '');
            $res = model('reg', 'logic')->reg(['phone' => $phone, 'code' => $code, 'pwd' => $pwd, 'inviter' => $inviter]);
            $this->ajaxReturn($res);
        }
    }

    public function second() {
        $user_id = isLogin();
        if (!$user_id) {
            $this->error('请先注册!');
        }
        $user = model('user')->getUser(['user_id' => $user_id]);
        if (!$user) {
            $this->error('请先注册!');
        }
        if ($user['password'] != '') {
            $this->error('您已修改密码!', url('/account'));
        }
        return $this->fetch();
    }

    public function secondCheck(Request $request) {
        if ($request->isPost()) {
            $user_id = $request->post('user_id');
            if (!$user_id) {
                return ['code' => 0, 'msg' => '请先注册!'];
            }
            $user = model('user')->getUser(['user_id' => $user_id]);
            if (!$user) {
                return ['code' => 0, 'msg' => '请先注册!'];
            }
            if ($user['password'] != '') {
                return ['code' => 0, 'msg' => '您已修改密码!'];
            }
            return ['code' => 1, 'msg' => 'success'];
        }
    }

    public function secondProcess(Request $request) {
        if ($request->isPost()) {
            $user_id = $request->post('user_id') ?: isLogin();
            $re = model('reg', 'logic')->second([
                    'pwd' => $request->post('pwd'),
                    'cpwd' => $request->post('cpwd'),
                    'inviter' => $request->post('inviter'),
                    'user_id' => $user_id
            ]);
            return $re;
        }
    }
}
